package com.rjwh.dingdong.client.activity.radio;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.aishua.lib.utils.AsStrUtils;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.player.fragment.PlayerToolbarFragment;
import com.rjwh.dingdong.client.adapter.RadioAlbumProgramListAdapter;
import com.rjwh.dingdong.client.bean.localbean.PlayList;
import com.rjwh.dingdong.client.bean.localbean.RadioAnchorInfo;
import com.rjwh.dingdong.client.bean.localbean.Song;
import com.rjwh.dingdong.client.mvp.presenter.impl.RadioAlbumProgramPresenter;
import com.rjwh.dingdong.client.mvp.view.RadioAlbumProgramView;
import com.rjwh.dingdong.client.player.IPlayback;
import com.rjwh.dingdong.client.player.PlayConstants;
import com.rjwh.dingdong.client.player.PlayState;
import com.rjwh.dingdong.client.service.PlaybackService;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.RxBus;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Subscriber;

/**
 * @author Kay
 * @ClassName RadioChildMusicListActivity
 * @Description 儿歌节目列表
 * @date 2016-11-17
 * @history 2016-11-17 author: description:
 */
public class RadioChildMusicListActivity extends BaseActivity implements RadioAlbumProgramView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.radio_child_music_list_lv)
    ListView radioChildMusicListLv;
    @BindView(R.id.loading_layout)
    RelativeLayout loadingLayout;
    @BindView(R.id.error_layout)
    RelativeLayout errorLayout;
    private RadioAlbumProgramListAdapter adapter;

    private RadioAlbumProgramPresenter presenter;
    private String anchorid;
    private String albumid;
    private Observable<Song> observableUpdateSong;
    private Observable<PlayState> observablePlayState;
    private IPlayback mPlayer;
    private int currentIndex = -1;
    private PlayList playList = new PlayList();
    private String albumname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.radio_child_music_list_layout);
        ButterKnife.bind(this);
        parseIntent();
        initObserver();
        initView();
        presenter = new RadioAlbumProgramPresenter(this, this);
        presenter.subscribe();
        doGetAlbumProgramList();
    }

    private void doGetAlbumProgramList() {
        hideErrorView();
        showLoadingView();
        presenter.doGetRadioAlbumProgramList(anchorid, albumid);
    }

    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            anchorid = intent.getStringExtra("anchorid");
            albumid = intent.getStringExtra("albumid");
            albumname = intent.getStringExtra("albumname");
        }
    }

    private void initObserver() {
        observableUpdateSong = RxBus.get().register(PlayConstants.ACTION_UPDATA_SONG, Song.class);
        observablePlayState = RxBus.get().register(PlayConstants.ACTION_PLAY_STATUS_CHANGED, PlayState.class);
        addSubscription(observableUpdateSong, subscriberUpdateSong);
        addSubscription(observablePlayState, subscriberPlayState);
    }

    private void initView() {
        initToolbarHelper();
        getSupportFragmentManager().beginTransaction().replace(R.id.radio_child_music_list_fm, PlayerToolbarFragment.getInstance()).commit();
        adapter = new RadioAlbumProgramListAdapter(this);
        radioChildMusicListLv.setAdapter(adapter);
        radioChildMusicListLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                if (mPlayer != null) {
//                    LogUtil.d("playList:" + playList.getSongs().size() + " position" + position);
//                    mPlayer.play(playList, position);
//                    currentIndex = position;
//                    updataListViewSelectState(position);
//
//                }
                if (mPlayer != null && playList != null) {
                    if (playList.getSongs().isEmpty()) {
                        //没有播放歌曲
                        LogUtil.d("playList:" + playList.getSongs().size() + " position" + position);
                        currentIndex = position;
                        mPlayer.play(playList, currentIndex);
                    } else {
                        //正在播放歌曲
                        if (currentIndex == position) {
                            //点击的是播放的条目
                            if (mPlayer.isPlaying()) {
                                mPlayer.pause();
                            } else {
                                mPlayer.play();
                            }
                        } else {
                            //点击的不是播放的条目
                            currentIndex = position;
                            mPlayer.play(playList, currentIndex);
                        }
                    }
                    LogUtil.e("RadioAlbumProgramActivi", "currentIndex:" + currentIndex);
                    updataListViewSelectState(currentIndex);
                }
            }
        });
    }

    protected void initToolbarHelper() {
        this.setSupportActionBar(this.toolbar);
        assert getSupportActionBar() != null;
        if (!AsStrUtils.isEmpty(albumname)) {
            getSupportActionBar().setTitle(albumname);
        }
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void showLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideLoadingView() {
        if (loadingLayout != null) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void showErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideErrorView() {
        if (errorLayout != null) {
            errorLayout.setVisibility(View.GONE);
        }
    }

    @Override
    public void loadData(RadioAnchorInfo basicinfo, List<Song> programlist) {
        playList.setSongs(programlist);
        adapter.clearAll();
        adapter.appendToList(programlist);
        if (mPlayer != null) {
            updataListViewSelectState(mPlayer.getPlayingSong());
        }
    }

    @Override
    public void onPlaybackServiceBound(PlaybackService service) {
        mPlayer = service;
    }

    @Override
    public void onPlaybackServiceUnbound() {
        mPlayer = null;
    }

    @Override
    public void onSongUpdated(@Nullable Song song) {
        //绑定服务成功以后去刷新列表中的状态
        if (adapter != null && !adapter.isEmpty()) {
            updataListViewSelectState(song);
        }
    }

    @Override
    public void updatePlayToggle(PlayState change) {
        adapter.setSelectIndex(change);
    }

    //刷新选中状态
    public void updataListViewSelectState(Song song) {
        //播放结束
        if (song == null) {
            currentIndex = -1;
            adapter.setSelectIndex(currentIndex, PlayState.STOP);
            return;
        }
        for (int i = 0, j = adapter.getList().size(); i < j; i++) {
            Song radioAlbumProgramData = adapter.getList().get(i);
            if (song.getProgramid().equals(radioAlbumProgramData.getProgramid())) {
                //自动播放
                currentIndex = i;
                if (mPlayer != null) adapter.setSelectIndex(i, mPlayer.getPlayStatus());
                break;
            }
        }
    }

    //刷新选中状态
    public void updataListViewSelectState(int index) {
        if (mPlayer != null) adapter.setSelectIndex(index, mPlayer.getPlayStatus());
    }

    //刷新播放的状态
    public void updataListViewItemPlayState(PlayState change) {
        if (currentIndex == -1) return;
        adapter.setSelectIndex(change);
    }

    Subscriber subscriberUpdateSong = new Subscriber<Song>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }


        @Override
        public void onNext(Song song) {
            updataListViewSelectState(song);
        }
    };

    Subscriber subscriberPlayState = new Subscriber<PlayState>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {

        }


        @Override
        public void onNext(PlayState change) {
            updataListViewItemPlayState(change);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
        RxBus.get().unregister(PlayConstants.ACTION_UPDATA_SONG, observableUpdateSong);
        RxBus.get().unregister(PlayConstants.ACTION_PLAY_STATUS_CHANGED, observablePlayState);
    }
}
